package org.giantlizard.cloud.user.token.service.impl;

import com.giantlizard.cloud.common.security.constants.SecurityConstants;
import com.giantlizard.cloud.common.security.model.LoginUser;
import com.giantlizard.cloud.common.security.utils.JwtTokenUtil;
import com.giantlizard.cloud.redis.utils.RedisOperator;
import org.giantlizard.cloud.user.token.base.CurrentLoginUser;
import org.giantlizard.cloud.user.token.entity.User;
import org.giantlizard.cloud.user.token.service.UserAuthentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Service("giantlizardUserAuthentication")
public class UserAuthenticationImpl implements UserAuthentication {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private final CurrentLoginUser currentLoginUser;
    private final RedisOperator redisOperator;

    public UserAuthenticationImpl(CurrentLoginUser currentLoginUser, RedisOperator redisOperator) {
        this.currentLoginUser = currentLoginUser;
        this.redisOperator = redisOperator;
    }

    @Override
    public User getCurrentUser(HttpServletRequest request, HttpServletResponse response) {
        currentLoginUser.setUser(null);

        LoginUser userInfo=getUser(request,response);
        if(userInfo!=null){
            User user=new User();
            user.setId(userInfo.getUserId());
            user.setUsername(userInfo.getUsername());
            List<String> deptIdList=userInfo.getPermissions();
            user.setDeptIdList(deptIdList);
            currentLoginUser.setUser(user);
            return user;
        }
        return null;
    }

    private LoginUser getUser(HttpServletRequest request, HttpServletResponse response){
        try{
            String token = JwtTokenUtil.getToken(request);
            return (LoginUser) redisOperator.getObj(SecurityConstants.LOGIN_TOKEN_KEY + token);
        }catch (Exception e){
            logger.error("", e);
        }
        return null;
    }
}
